/*
 *-------------------------------------------------------------
 *    copyrights by
 *    	Bartosz "Dust" Kowalski (dustization.info)
 *    	Maciej Krzysica 
 *-------------------------------------------------------------
 *    Plik: 	PCMModulation.java
 */

package core;

class PCMModulation implements PCMOperation {

	private int interval = 0;
	
	private boolean recalculate = true;
	
	private double currentValue = 0;

	@Override
	public PCMOperationData operate(DataPackage dataPackage, PCMSettings settings) {
		
		if(recalculate)
		{
			interval = (int) (dataPackage.sampleRate / (settings.getSampleRate()));
			recalculate = false;
			
			//here comes quantization
			currentValue = quantization(dataPackage.data[0], settings.getResolution());
		}
		dataPackage.data[0] = currentValue;
		
		if ( --interval == 0 )
			recalculate = true;
		
		return new PCMOperationData(dataPackage, true);

	}
	
	private double quantization(double value, int resolution)
	{
		double step = 2.0 / (1<<resolution);
		double start = 1.0;
		double stop = start - step;
		int code = 0;
		while(stop >= -1.0)
		{
			if(value < start && value > stop)
			{
				value = code;
				break;
			}
			else
			{
				start -= step;
				stop -= step;
				code++;
			}
		}
		return value;
	}

}
